﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.ComponentModel;

namespace Viinikellari
{
    [XmlRoot("viinikellari")]
    public class WineCollection : INotifyPropertyChanged
    {
        public WineCollection()
        {
            Wines = new List<Wine>();
        }

        [XmlElement("wine")]
        public List<Wine> Wines { get; set; }

        string selectedCountry;
        [XmlIgnore]
        public string SelectedCountry
        {
            get { return selectedCountry; }
            set
            {
                SetField(ref selectedCountry, value, "SelectedCountry");
                NotifyChanged("WinesbyCountry");
                NotifyChanged("Summary");
            }
        }

        [XmlIgnore]
        public IEnumerable<string> Countries
        {
            get
            {
                yield return Resources.Strings.WineCollectionAllCountries;

                foreach (var c in Wines.Select(s => s.Country).Distinct())
                    yield return c;
            }
        }

        [XmlIgnore]
        public IEnumerable<Wine> WinesByCountry
        {
            get
            {
                if (string.IsNullOrEmpty(SelectedCountry) ||
                    selectedCountry == Resources.Strings.WineCollectionAllCountries)
                    return Wines;

                return Wines.Where(p => p.Country == SelectedCountry);
            }
        }

        [XmlIgnore]
        public string Summary
        {
            get
            {

                if (string.IsNullOrEmpty(SelectedCountry) ||
                    selectedCountry == Resources.Strings.WineCollectionAllCountries)
                    return string.Format(Resources.Strings.WineCollectionSummaryFormat, Countries.Count(), Wines.Count);
                else
                    return string.Format(Resources.Strings.WineCollectionSummaryByCountryFormat, Countries.Count(), Wines.Count, WinesByCountry.Count(), SelectedCountry);
            }
        }

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        protected void SetField<T>(ref T field, T value, string propertyName)
        {
            if (EqualityComparer<T>.Default.Equals(field, value))
                return;

            field = value;

            NotifyChanged(propertyName);
        }

        #endregion
    }
}
